package codeRandomThoughts.Test110平衡二叉树;

import codeRandomThoughts.utils.TreeNode;

public class Solution {
    public boolean isBalanced(TreeNode root) {
        return isBl(root).isBalanced;
    }

    public R isBl(TreeNode root) {
        if (root == null) {
            return new R(0, true);
        }
        TreeNode left = root.left;
        TreeNode right = root.right;
        R leftR = isBl(left);
        R rightR = isBl(right);
        if (!leftR.isBalanced || !rightR.isBalanced)
            return new R(false);
        if (Math.abs(leftR.depth - rightR.depth) > 1) {
            return new R(false);
        } else {
            int depth = Integer.max(leftR.depth, rightR.depth) + 1;
            return new R(depth, true);
        }
    }

    class R {
        int depth;
        boolean isBalanced;

        public R() {
        }

        public R(boolean isBalanced) {
            this.isBalanced = isBalanced;
        }

        public R(int depth, boolean isBalanced) {
            this.depth = depth;
            this.isBalanced = isBalanced;
        }
    }
}
